<?php
// +----------------------------------------------------------------------
// | ShopXO 国内领先企业级B2C免费开源电商系统
// +----------------------------------------------------------------------
// | Copyright (c) 2011~2099 http://shopxo.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( https://opensource.org/licenses/mit-license.php )
// +----------------------------------------------------------------------
// | Author: Devil
// +----------------------------------------------------------------------
namespace app\index\controller;

/**
 * 支付
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2016-12-01T21:51:08+0800
 */
class Pay extends Common
{
    /**
     * 构造方法
     * @author   Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2018-11-30
     * @desc    description
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 二维码支付展示
     * @author   Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2018-09-28
     * @desc    description
     */
    public function Qrcode()
    {
        if(!empty($this->data_request['url']) && !empty($this->data_request['order_no']) && !empty($this->data_request['name']) && !empty($this->data_request['msg']))
        {
            return MyView();
        }
        MyViewAssign('msg', MyLang('params_error_tips'));
        return MyView('public/tips_error');
    }

    public function Fanyi()
    {
        set_time_limit(0);
        $data = file_get_contents(public_path() . 'cht.json');
        $json = json_decode($data, true);

        $newData = [];
        $error = "";
        foreach ($json as $k => &$item) {
            if(is_array($item)) {
                foreach ($item as $vk => $v) {
                    if(is_array($v)) {
                        foreach ($v as $vk2 => $vkv) {
                            if(!empty($vkv)) {
                                $res = $this->translate($vkv, 'zh', 'en');
                                if(!isset($res['error_code'])) {
                                    $newData[$k][$vk][$vk2] = $res['trans_result'][0]['dst'];
                                } else {
                                    $newData[$k][$vk][$vk2] = $vkv;
                                    $error .= $k . '--'. $vk . '--' .  $vk2 . '--' . $vkv . $res['error_msg'] . PHP_EOL;
                                }
                            } else {
                                $newData[$k][$vk][$vk2] = $vkv;
                            }
                        }
                    } else {
                        if($v) {
                            $res = $this->translate($v, 'zh', 'en');
                            if(!isset($res['error_code'])) {
                                $newData[$k][$vk] = $res['trans_result'][0]['dst'];
                            } else {
                                $newData[$k][$vk] = $v;
                                $error .= $k . '--'. $vk . '--' . $v . $res['error_msg'] . PHP_EOL;
                            }
                        } else {
                            $newData[$k][$vk] = $v;
                        }

                    }
                }
            } else {
                if(!empty($item)) {
                    $res = $this->translate($item, 'zh', 'en');
                    if(!isset($res['error_code'])) {
                        $newData[$k] = $res['trans_result'][0]['dst'];
                    } else {
                        $newData[$k] = $item;
                        $error .= $k . '--'. $item . $res['error_msg'] . PHP_EOL;
                    }
                } else {
                    $newData[$k] = $item;
                }
            }
        }
        print_r($error);
        echo PHP_EOL;
        $re = file_put_contents(public_path() . 'cht222.json', json_encode($newData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
        echo $re;
    }
    //翻译入口
    public function translate($query, $from, $to)
    {
        $args = array(
            'q' => $query,
            'appid' => '1226002238874',
            'salt' => rand(10000,99999),
            'from' => $from,
            'to' => $to,

        );
        $args['sign'] = $this->buildSign($query, '1226002238874', $args['salt'], 'r2LuoUNyy6ieSVmfqk');
        $ret = $this->call("http://api.fanyi.baidu.com/api/trans/vip/translate", $args);
        $ret = json_decode($ret, true);
        return $ret;
    }

//加密
    public function buildSign($query, $appID, $salt, $secKey)
    {/*{{{*/
        $str = $appID . $query . $salt . $secKey;
        $ret = md5($str);
        return $ret;
    }/*}}}*/

//发起网络请求
    public function call($url, $args=null, $method="post", $testflag = 0, $timeout = 10, $headers=array())
    {/*{{{*/
        $ret = false;
        $i = 0;
        while($ret === false)
        {
            if($i > 1)
                break;
            if($i > 0)
            {
                sleep(1);
            }
            $ret = $this->callOnce($url, $args, $method, false, $timeout, $headers);
            $i++;
        }
        return $ret;
    }/*}}}*/

    public function callOnce($url, $args=null, $method="post", $withCookie = false, $timeout = 10, $headers=array())
    {/*{{{*/
        $ch = curl_init();
        if($method == "post")
        {
            $data = $this->convert($args);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_POST, 1);
        }
        else
        {
            $data = $this->convert($args);
            if($data)
            {
                if(stripos($url, "?") > 0)
                {
                    $url .= "&$data";
                }
                else
                {
                    $url .= "?$data";
                }
            }
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if(!empty($headers))
        {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }
        if($withCookie)
        {
            curl_setopt($ch, CURLOPT_COOKIEJAR, $_COOKIE);
        }
        $r = curl_exec($ch);
        curl_close($ch);
        return $r;
    }/*}}}*/

    public function convert(&$args)
    {/*{{{*/
        $data = '';
        if (is_array($args))
        {
            foreach ($args as $key=>$val)
            {
                if (is_array($val))
                {
                    foreach ($val as $k=>$v)
                    {
                        $data .= $key.'['.$k.']='.rawurlencode($v).'&';
                    }
                }
                else
                {
                    $data .="$key=".rawurlencode($val)."&";
                }
            }
            return trim($data, "&");
        }
        return $args;
    }/*}}}*/

    public function payBBMsl($params = [])
    {
        $domain = MyConfig('shopxo.domain_url');
        $merchantId = env('MERCHANT_ID');
        $payment_url = env('PAYMENT_URL');

        $url_fail = $domain.'test_bbmsl_fail.php';
        $url_success = $domain.'test_bbmsl_success.php';
        $url_cancel = $domain.'test_bbmsl_cancel.php';
        $url_notify = $domain.'test_bbmsl_notify.php';

        $merchant_ref = 'merchantRef'.date('YmdHis');
        $quantity = 1;
        $amount = 10;
        $product_name = 'Book';

        $arr_request = [
            'merchantId' => $merchantId,
            'amount' => $params[''],
            'isRecurring'=> 0,
            'callbackUrl' => [
                "fail" => $url_fail,
                "success" => $url_success,
                "cancel" => $url_cancel,
            ],
            'merchantReference' => $merchant_ref,
            "lineItems" => [
                [
                    "quantity" => $quantity,
                    'priceData' => [
                        "unitAmount" => $amount,
                        "name" => $product_name
                    ]
                ]
            ],
        ];

        $request_content = json_encode($arr_request, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

        // 2. if you include the .pem file
        $key = openssl_pkey_get_private(file_get_contents(env('PRIVATE_KEY_FILE')));

        if (!$key) {
            echo "Invalid key format".PHP_EOL;
            exit;
        }

        echo '==========================='.PHP_EOL;
        echo 'sign request'.PHP_EOL;
        echo '==========================='.PHP_EOL;

        openssl_sign($request_content, $encrypted, $key, OPENSSL_ALGO_SHA256);

        $signature = base64_encode($encrypted);

        $url =  $payment_url . env('HOSTED_MODEL_URL');

        // Create a new cURL resource
        $ch = curl_init($url);

        echo '===========================';
        echo PHP_EOL;
        echo 'request for signature';
        echo PHP_EOL;
        echo '===========================';
        echo PHP_EOL;
        echo $request_content;

        echo PHP_EOL;
        echo '===========================';
        echo PHP_EOL;
        echo 'signature';
        echo PHP_EOL;
        echo '===========================';
        echo PHP_EOL;
        echo $signature;

        $arr_payload = array(
            "request" => $request_content,
            'signature' => $signature
        );

        $payload = json_encode($arr_payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

        echo PHP_EOL;
        echo "URL: ".$url ;
        echo PHP_EOL;
        echo "Request:".$payload;
        echo PHP_EOL;

        // Attach encoded JSON string to the POST fields
        curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);

        // Set the content type to application/json
        curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json'));

        // Return response instead of outputting
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, 1);

        // Execute the POST request
        $result = curl_exec($ch);

        // Get the POST request header status
        $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        // Close cURL resource
        curl_close($ch);

        // if you need to process the response from the API further
        $response = json_decode($result, true);

        print_r($response);
        echo "Response: " . $result;
    }
}
?>